package com.weave.view;

import com.weave.model.GameModel;

import javax.swing.*;
import java.awt.*;


public class WordGridPanel extends JPanel {
    private final GameModel model;

    public WordGridPanel(GameModel model) {
        this.model = model;
        setLayout(new GridLayout(0, 1, 5, 5));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();

        // 绘制代码
        java.util.List<String> steps = model.getSteps();
        int y = 30;
        for (String word : steps) {
            drawWordRow(g2d, word, y);
            y += 50;
        }

        y += 100;
        drawWordRow(g2d, model.getTargetWord(), y);
        g2d.dispose();
    }


    private void drawWordRow(Graphics g, String word, int yPos) {
        String target = model.getTargetWord();

        for (int i = 0; i < GameModel.WORD_LENGTH; i++) {
            char c = word.charAt(i);
            Color bgColor = calculateColor(c, i, target);

            g.setColor(bgColor);
            g.fillRect(i * 60, yPos, 55, 45);

            g.setColor(Color.BLACK);
            g.drawString(String.valueOf(c), i * 60 + 25, yPos + 25);
        }
    }

    private Color calculateColor(char c, int position, String target) {
        if (c == target.charAt(position)) {
            return Color.GREEN;
        } else if (target.indexOf(c) == -1) {
            return Color.GRAY;
        } else {
            return Color.LIGHT_GRAY;
        }
    }
}
